package com.graduation.lastproject.util.shiro;

import com.graduation.lastproject.entity.Business;
import com.graduation.lastproject.service.business.businessBasicActive.BusinessService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class BusinessRealm extends AuthorizingRealm{
    private static Logger logger=LoggerFactory.getLogger(BusinessRealm.class);

    @Autowired
    private BusinessService businessService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //把AuthenticationToken转换为LoginsToken
        LoginsToken loginsToken=(LoginsToken) authenticationToken;
        //获取登录名
        String loginname= loginsToken.getPrincipal()+"";
        logger.info("loginname:-------"+loginname+"----------loginsToken:"+loginsToken.toString());
        //查询用户信息
        Business business=businessService.getByLogsinName(loginname);
        logger.info("business:-------"+business);
        if(business!=null){
            // 根据用户的情况，来构建AuthenticationInfo对象并返回，通常使用的实现类为SimpleAuthenticationInfo
            //验证身份
            SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo("",business.getBpassword(),"xxx");
            logger.info("返回商家对象:"+authenticationInfo);
            //消费者使用shiro标签判断 前端获取 logout方法退出  有问题哦 都用el标签吧
            //商家使用el标签判断   退出的话使用removeAttrbute()
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            session.setAttribute("businessInfo",business);
            session.setAttribute("business",business.getBrealname());
            logger.info("商家logger:--"+business);
            return  authenticationInfo;
        }
        return null;
    }
}
